package com.ququ.syb.mqhandler.service;

import com.ququ.syb.common.constant.PayChannelClearTypeConstant;
import com.ququ.syb.common.constant.WithdrawStatusConstant;
import com.ququ.syb.common.pojo.PayChannel;
import com.ququ.syb.common.pojo.PayOrder;
import com.ququ.syb.common.pojo.WithdrawOrder;
import com.ququ.syb.mqhandler.fegin.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WithdrawVirtualService {

    private Logger logger = LoggerFactory.getLogger(WithdrawVirtualService.class);
    @Autowired
    private ChannelsRouterFegin channelsRouterFegin;
    @Autowired
    private WithdrawOrderFegin withdrawOrderFegin;
    @Autowired
    private WithdrawBusinessFegin withdrawBusinessFegin;
    @Autowired
    private PayChannelFegin payChannelFegin;
    @Autowired
    private PayOrderFegin payOrderFegin;

    public void doWithdraw(String tradenum){
        WithdrawOrder withdrawOrder = withdrawOrderFegin.queryWithdrawOrder(tradenum).getData();
        if (withdrawOrder == null){
            logger.error("{}提现订单不存在",tradenum);
            return;
        }
        if (withdrawOrder.getStatus() != WithdrawStatusConstant.AUDIT_SUCCESS){
            logger.error("{}提现订单不是审核完成状态，无法重复调用通道提现接口",tradenum);
            return;
        }
        if (StringUtils.isBlank(withdrawOrder.getPaytradenum())){
            logger.error("{}虚拟提现订单没有对应的支付订单号",tradenum);
            return;
        }
        PayChannel payChannel = payChannelFegin.getPayChannel(withdrawOrder.getPaychannelid()).getData();
        if (payChannel.getIsAutoClear() != PayChannelClearTypeConstant.REAL_DIRECT_CLEAR){
            logger.error("{}通道不是直清通道，不允许虚拟提现",withdrawOrder.getPaychannelid());
            return;
        }
        PayOrder payOrder = payOrderFegin.getPayOrder(withdrawOrder.getPaytradenum()).getData();
        if (payOrder.getDivideinfo() == null && withdrawOrder.getAmount() != payOrder.getAmount()-payOrder.getPayeecommission()){
            logger.error("{}提现订单的金额与支付订单{}不匹配",tradenum,payOrder.getTradenum());
            return;
        }
        //提现操作成功，等待回调
        withdrawOrder.setExcutetime(new Date());
        withdrawOrder.setStatus(WithdrawStatusConstant.ACCEPTING);
        withdrawOrderFegin.updateWithdrawOrder(withdrawOrder);
        //接口成功直接设置订单为成功
        withdrawBusinessFegin.withdrawCallback(tradenum,1,"交易成功");
    }
}
